/**
 * Panel affichant les informations sur le mail et permettant l'envoi
 * @author Marie-Hélène Goddet, Damien Finck, Cédric Schaller
 * 
 */
package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import utils.Debug;
import utils.Resources;
import fastwriting.FastWriting;

@SuppressWarnings("serial")
public class JSend extends JPanel {
	
	private ActionListener actionListener;
	
	protected JPanel jp_to;
		protected JPanel jp_to_gauche;
			protected JLabel jl_to;
			protected JButton jb_to;
		protected JTextArea jta_to;
	protected JPanel jp_message;
		protected JPanel jp_message_gauche;
			protected JLabel jl_message;
			protected JButton jb_modifier;
		protected JTextArea jta_message;
	protected JPanel jp_bas;
		protected JButton jb_home,jb_envoyer;
		protected JLabel jl_etat;
	/**
	 * Constructeur
	 */
	public JSend() {
		/** Événements **/
		ActionListener action = new Event_JPSend(this);
		MouseListener mouse = new Event_JPSend(this);
		/** Création des éléments     **/
		this.jp_to = new JPanel(new BorderLayout());
			this.jp_to_gauche = new JPanel(new BorderLayout());
				this.jl_to = new JLabel("A :");
				this.jb_to = new JButton("Contacts");
			this.jta_to = new JTextArea();
		this.jp_message = new JPanel(new BorderLayout());
			this.jp_message_gauche = new JPanel(new BorderLayout());
				this.jl_message = new JLabel("Message :");
				this.jb_modifier = new JButton("Modifier");
			this.jta_message = new JTextArea();
		this.jp_bas = new JPanel();
			this.jb_home = new JButton("Accueil",Resources.getImageIcon("images/home.png",getClass()));
			this.jb_envoyer = new JButton("Envoyer",Resources.getImageIcon("images/mail.png",getClass()));
			this.jl_etat = new JLabel();
		/** Paramétrage des éléments  **/
		this.setLayout(new BorderLayout());
		this.jta_to.setRows(2);
		//this.jta_message.setRows(10);
		
		this.jta_to.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
		this.jta_message.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
		
		this.jta_to.setLineWrap(true);		// aller a la ligne automatiquement
		this.jta_to.setWrapStyleWord(true);	//ne pas couper les mots
		
		this.jta_message.setLineWrap(true);		// aller a la ligne automatiquement
		this.jta_message.setWrapStyleWord(true);	//ne pas couper les mots
		/** Action sur les éléments   **/
		this.jb_home.addActionListener(action);
		this.jb_to.addActionListener(action);
		this.jb_modifier.addActionListener(action);
		this.jb_envoyer.addMouseListener(mouse);
		/** Montage des éléments      **/
		this.add(this.jp_to,BorderLayout.NORTH);
			this.jp_to.add(this.jp_to_gauche,BorderLayout.WEST);
				this.jp_to_gauche.add(this.jl_to,BorderLayout.NORTH);
				this.jp_to_gauche.add(this.jb_to,BorderLayout.SOUTH);
			this.jp_to.add(this.jta_to,BorderLayout.CENTER);
		this.add(this.jp_message,BorderLayout.CENTER);
			this.jp_message.add(this.jp_message_gauche,BorderLayout.WEST);
				this.jp_message_gauche.add(this.jl_message,BorderLayout.NORTH);
				this.jp_message_gauche.add(this.jb_modifier,BorderLayout.SOUTH);
			this.jp_message.add(this.jta_message,BorderLayout.CENTER);
		this.add(this.jp_bas,BorderLayout.SOUTH);
			this.jp_bas.add(this.jb_home);
			this.jp_bas.add(this.jb_envoyer);
			this.jp_bas.add(this.jl_etat);
	}
	public void addActionListener(ActionListener actionListener) {
		this.actionListener = actionListener;
	}
	public ActionListener getActionListener() {
		return actionListener;
	}
}
class Event_JPSend implements ActionListener, MouseListener {
	JSend jp;
	/**
	 * Constructeur
	 * @param jp le panel d'envoi
	 */
	public Event_JPSend(JSend jp) {
		this.jp=jp;
	}
	@Override
	public void actionPerformed(ActionEvent arg0) {
		Object obj = arg0.getSource();
		if (obj instanceof JButton) {
			JButton jb = (JButton)obj;
			if (jb==jp.jb_home) {
				ActionEvent e = new ActionEvent(jp,1001,"JSend_home");
				jp.getActionListener().actionPerformed(e);
			} else if (jb==jp.jb_modifier) {
				ActionEvent e = new ActionEvent(jp,1001,"JSend_message");
				jp.getActionListener().actionPerformed(e);
			} else if (jb==jp.jb_to) {
				ActionEvent e = new ActionEvent(jp,1001,"JSend_contact");
				jp.getActionListener().actionPerformed(e);
			}
		}
	}
	@Override
	public void mouseClicked(MouseEvent arg0) {
		
	}
	@Override
	public void mouseEntered(MouseEvent arg0) {
		
	}
	@Override
	public void mouseExited(MouseEvent arg0) {
		
	}
	@Override
	public void mousePressed(MouseEvent arg0) {
		
	}
	/**
	 * Appelée lors du relâchement de la touche d'envoi de mail
	 */
	@Override
	public void mouseReleased(MouseEvent arg0) {
		Object obj = arg0.getSource();
		if (obj instanceof JButton) {
			JButton jb = (JButton)obj;
			if (jb==jp.jb_envoyer) {
				String nom=FastWriting.config.get("Utilisateur").get("Nom").toString();
				String mail=FastWriting.config.get("Utilisateur").get("Mail").toString();
				final String emailMsgTxt = jp.jta_message.getText()+"\n\n-----\nCe message vous a été envoyé avec FastWriting !";
				final String emailSubjectTxt = "Mail envoyé via l'application FastWriting";
				final String emailFromAddress = nom+" <"+mail+">";
				String temp = jp.jta_to.getText().substring(0,jp.jta_to.getText().lastIndexOf(","));
				final String[] sendTo = temp.split(",");
				
				try {
					//Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
					sendMail(sendTo, emailSubjectTxt,emailMsgTxt, emailFromAddress);
				} catch (MessagingException e) {
					jp.jl_etat.setText("Echec a l'envoie du mail !");
					jp.jl_etat.setIcon(Resources.getImageIcon("images/erreur.png",getClass()));
					e.printStackTrace();
				}
				jp.jl_etat.setText("Mail envoyé !");
				jp.jl_etat.setIcon(Resources.getImageIcon("images/sucess.png",getClass()));
				jp.jb_envoyer.setEnabled(false);
			}
		}
	}
	
	/**
	 * Envoie un email
	 * @param recipients Liste des destinataires
	 * @param subject Sujet du mail
	 * @param message Message de l'email
	 * @param from Expéditeur
	 * @throws MessagingException
	 */
	public void sendMail(String recipients[], String subject, String message, String from) throws MessagingException {
		Debug.addLog("START send e-mail",Debug.LOG_INFO,"all");
		
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.auth", "true");
		if (Debug.DEBUG && Debug.TAG.contains("mail")) props.put("mail.debug", "true");
		props.put("mail.smtp.port", "465");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");
		
		//props.put("mail.smtp.ssl.enable", "true");	// add by Damien
		
		Session session = Session.getDefaultInstance(props,
		new javax.mail.Authenticator() {
		
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication("fastwriting@gmail.com","fastwriting|swype");
			}
		});
		
		if (Debug.DEBUG && Debug.TAG.contains("mail")) session.setDebug(Debug.DEBUG);
		
		Message msg = new MimeMessage(session);
		InternetAddress addressFrom = new InternetAddress(from);
		msg.setFrom(addressFrom);
		
		InternetAddress[] addressTo = new InternetAddress[recipients.length];
		for (int i = 0; i < recipients.length; i++) {
			addressTo[i] = new InternetAddress(recipients[i]);
		}
		msg.setRecipients(Message.RecipientType.TO, addressTo);
		
		
		InternetAddress[] reply_to = {new InternetAddress(from)};
		msg.setReplyTo(reply_to);
		
		// Setting the Subject and Content Type
		msg.setSubject(subject);
		msg.setContent(message, "text/plain");
		Transport.send(msg);
		
		Debug.addLog("END send e-mail",Debug.LOG_INFO,"all");
	}
}